# -*- coding: utf-8 -*-
""" 
@author: ertao.xyz
@create: 2021-09-07 10:34
@description: 
"""
from typing import TYPE_CHECKING, Type, Dict, List

from tortoise.exceptions import DoesNotExist

from utils.response_code import ResultResponse
from utils import logger

if TYPE_CHECKING:  # pragma: nocoverage
    from tortoise.models import Model


async def get_obj_by_name(cls: "Type[Model]", name: str):
    """
    根据名字获取信息
    """
    try:
        obj = await cls.get(name=name)
    except DoesNotExist as exec:
        return None
    return obj


async def get_obj_by_id(cls: "Type[Model]", id: int):
    """
    根据ID获取信息
    """
    try:
        obj = await cls.get(pk=id)
    except DoesNotExist as exec:
        return None
    return obj


async def has_obj_by_name(cls: "Type[Model]", name: str) -> bool:
    """
    判断是否存在
    """
    obj = await get_obj_by_name(cls, name)
    if obj and not obj.is_delete:
        return True
    return False


async def create_obj(cls: "Type[Model]", data):
    obj = cls(**data.dict())
    await obj.save()
    return obj


async def delete_obj_by_ids(cls: "Type[Model]", ids: list):
    if len(ids) > 20:
        return ResultResponse(message='最多一次删除20行', code=421)
    obj = await cls.filter(id__in=ids).update(is_delete=1)
    if obj:
        # await obj.save()
        return True
    return False


async def update_obj_by_id(cls: "Type[Model]", id: int, data: Dict):
    obj = await get_obj_by_id(cls, id)
    obj = await obj.update_from_dict(data).save()
    return obj
